package main

import (
	"fmt"
	"github.com/google/cel-go/cel"
	"log"
)

// 当日用户在线时长 > 5分钟
// 当日用户充值总金额 > 100元
// 转盘抽奖，不同条件不同概率

func main() {
	init1()
	return

	// 创建CEL环境并声明profit变量
	env, err := cel.NewEnv(
		cel.Variable("userOnlineDuration", cel.IntType),
		cel.Variable("configOnlineDuration", cel.IntType),
		cel.Variable("userTotalRechargeAmount", cel.IntType),
		cel.Variable("configTotalRechargeAmount", cel.IntType),
	)
	if err != nil {
		panic(fmt.Sprintf("环境创建失败: %v", err))
	}

	userOnlineDuration := 100
	configOnlineDuration := 50

	userTotalRechargeAmount := 90
	configTotalRechargeAmount := 100

	//expr := `
	//	profit < 1000 ? double(profit) * 0.1 :
	//	profit > 1000 && profit < 2000 ? double(profit) * 0.15 :
	//	profit > 2000 && profit < 3000 ? double(profit) * 0.2 :
	//	double(profit) * 0.3
	//`

	expr := `
		userOnlineDuration >= configOnlineDuration && userTotalRechargeAmount >= configTotalRechargeAmount
	`

	// 编译表达式
	ast, iss := env.Compile(expr)
	if iss.Err() != nil {
		panic(fmt.Sprintf("编译错误: %v", iss.Err()))
	}

	// 生成可执行程序
	prg, err := env.Program(ast)
	if err != nil {
		panic(fmt.Sprintf("程序生成错误: %v", err))
	}

	out, _, err := prg.Eval(map[string]interface{}{
		"userOnlineDuration":        userOnlineDuration,
		"configOnlineDuration":      configOnlineDuration,
		"userTotalRechargeAmount":   userTotalRechargeAmount,
		"configTotalRechargeAmount": configTotalRechargeAmount,
	})
	if err != nil {
		panic(fmt.Sprintf("评估错误: %v", err))
	}

	if v, ok := out.Value().(bool); ok {
		fmt.Printf("结果:%v\n", v)
	}

}

func init1() {
	// 定义环境：暴露 user、resource 变量
	env, err := cel.NewEnv(
		cel.Variable("user", cel.MapType(cel.StringType, cel.AnyType)),
		cel.Variable("resource", cel.MapType(cel.StringType, cel.AnyType)),
	)
	if err != nil {
		log.Fatal(err)
	}

	// 编译规则：用户是资源所有者或管理员
	rule := `user.roles.contains('admin') || resource.owner == user.id`
	ast, iss := env.Compile(rule)
	if iss.Err() != nil {
		log.Fatal(iss.Err())
	}

	// 构建可执行程序
	prg, err := env.Program(ast)
	if err != nil {
		log.Fatal(err)
	}

	// 求值：检查特定用户是否有权限
	out, _, err := prg.Eval(map[string]interface{}{
		"user": map[string]interface{}{
			"id":    "123",
			"roles": []string{"editor"},
		},
		"resource": map[string]interface{}{
			"owner": "123",
		},
	})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("有权限: %v", out) // 输出: 有权限: true
}
